package com.sunday.scoremanager.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.ImageUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.utils.download.ImgUtils;
import com.sunday.scoremanager.R;
import com.sunday.scoremanager.base.AppConfig;
import com.sunday.scoremanager.base.BaseApp;
import com.sunday.scoremanager.entity.ShopQrCode;
import com.sunday.scoremanager.http.ApiClient;
import com.sunday.scoremanager.widgets.ShareWindow;
import com.umeng.socialize.UMShareAPI;

import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/10/27.
 */

public class MyQrCodeActivity extends BaseActivity {


    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.rightTxt)
    TextView rightTxt;
    @Bind(R.id.right_btn)
    ImageView rightBtn;
    @Bind(R.id.shop_name)
    TextView shopName;
    @Bind(R.id.qr_code_img)
    ImageView qrCodeImg;
    @Bind(R.id.btn_save)
    TextView btnSave;
    @Bind(R.id.btn_share)
    TextView btnShare;
    @Bind(R.id.left_btn)
    ImageView leftBtn;
    @Bind(R.id.common_header)
    RelativeLayout commonHeader;
    @Bind(R.id.txt)
    TextView txt;
    @Bind(R.id.view)
    View view;
    @Bind(R.id.layout_code)
    RelativeLayout layoutCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_qrcode);
        ButterKnife.bind(this);
        titleView.setText("店铺收款码");
        getData();

    }

    ShopQrCode shopQrCode;

    private void getData() {
        showLoadingDialog(0);
        Call<ResultDO<ShopQrCode>> call = ApiClient.getApiAdapter().sellerTowCode(BaseApp.getInstance().getMember().getSellerId());
        call.enqueue(new Callback<ResultDO<ShopQrCode>>() {
            @Override
            public void onResponse(Call<ResultDO<ShopQrCode>> call, Response<ResultDO<ShopQrCode>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    shopQrCode = response.body().getResult();
                    initView();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<ShopQrCode>> call, Throwable t) {
                dissMissDialog();
            }
        });
    }

    private void initView() {
        if (shopQrCode == null) {
            return;
        }
        Glide.with(mContext)
                .load(shopQrCode.getCodeUrl())
                .into(qrCodeImg);
        shopName.setText(shopQrCode.getSellerName());
    }

    @OnClick({R.id.btn_save, R.id.btn_share})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_save:
                if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    Toast.makeText(this, "没有外部权限", Toast.LENGTH_SHORT).show();
                    return;
                }
                new Handler().post(runnable);
                break;
            case R.id.btn_share:
                String shareUrl = ApiClient.SHARE_URL;
                ShareWindow shareWindow = new ShareWindow(mContext,shareUrl,mContext.getResources().getString(R.string.share_product_desc),
                     null ,"快点一起加入吧",null);
                shareWindow.showPopupWindow(rightBtn);
                break;
        }
    }

    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            viewSaveToImage(layoutCode);
        }
    };

    private void viewSaveToImage(View view) {
        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        view.setDrawingCacheBackgroundColor(Color.WHITE);

        // 把一个View转换成图片
        Bitmap cachebmp = loadBitmapFromView(view);

        Bitmap bitmap = Bitmap.createBitmap(cachebmp);
        final String filePath = AppConfig.DEFAULT_SAVE_IMAGE_PATH + ImageUtils.getFileNameForDate();
        try {
            ImgUtils.saveImageToSD(mContext, filePath, bitmap, 100);
            ToastUtils.showToast(mContext, "图片保存成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
//        String savePath=ImageUtils.saveBitmap(bitmap);
//        ImgUtils.scanPhoto(mContext,savePath);

        view.destroyDrawingCache();
    }

    private String getFileName(String imgUrl) {
        int index = imgUrl.lastIndexOf('/') + 1;
        if (index == -1) {
            return System.currentTimeMillis() + ".jpeg";
        }
        return imgUrl.substring(index);
    }

    private Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */
        int appWidth = DeviceUtils.getDisplay(mContext).widthPixels;
        int appHeight = DeviceUtils.getDisplay(mContext).heightPixels;
        v.layout((appWidth - w) / 2, (int) qrCodeImg.getY(), w + (appWidth - w) / 2, h + (int) qrCodeImg.getY());

        v.draw(c);

        return bmp;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

    }

}
